import React from "react";
import { connect } from "react-redux";

import { message, Popover, Table, Input } from "antd";
import SVGIcon from "components/SVGIcon";
import { deepCopy, messages, queryCurrencyPrecision } from "share/common";
import EditCell from "containers/pay/template/edit-cell";
import ListSelector from "components/list-selector";
import Condition from "components/condition";
const { If, Else } = Condition;

class AssociateContract extends React.Component {
  state = {
    contractColumns: [
      {
        title: messages("finance-9.key29") /*行号*/,
        dataIndex: "lineNumber",
        width: 50,
      },
      {
        title: messages("finance-9.key30") /*阶段名称*/,
        dataIndex: "stageName",
        width: 120,
      },
      {
        title: messages("finance-9.key31") /*可关联金额*/,
        dataIndex: "availableAmount",
        width: 120,
        render: (value, record) =>
          record.amount && record.amount > 0 ? this.filterMoney(value, queryCurrencyPrecision(record.currency)) : "-",
      },
      {
        title: messages("finance-9.key5") /*支付金额*/,
        dataIndex: "lineAvailableAmount",
        width: 150,
        render: (value, record) => (
          <EditCell
            value={typeof value === "number" && !isNaN(value) ? value : 0}
            disable={!this.props.editable}
            precision={queryCurrencyPrecision(record.currencyCode)}
            onChange={(editValue) => this.editCurrentPay(editValue, record)}
            style={{ textAlign: "right" }}
            max={record.amount && record.amount > 0 ? record.availableAmount : Infinity}
            min={0}
            render={(value) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode), true)}
          />
        ),
      },
      {
        title: messages("finance-9.key32") /*计划付款*/,
        dataIndex: "dueDate",
        width: 120,
        render: (value) => (value ? new Date(value).format("yyyy-MM-dd") : "-"),
      },
      {
        title: messages("finance-9.key128") /*付款条件*/,
        dataIndex: "paymentConditions",
        width: 120,
        render: (value) => (
          <Popover placement="topLeft" content={value}>
            {value || "-"}
          </Popover>
        ),
      },
    ],
    contract: [],
    showContractLineList: false,
  };

  getSortedContractLineIdString = (contract) => {
    return contract
      .sort((a, b) => a.contractLineId - b.contractLineId)
      .reduce((total, i) => "" + total + i.contractLineId + i.lineAvailableAmount, "");
  };

  componentDidMount() {
    this.setState({ contract: this.props.contract });
  }

  componentWillReceiveProps(nextProps) {
    if (
      this.props.contract.length !== nextProps.contract.length ||
      this.getSortedContractLineIdString(this.props.contract) !== this.getSortedContractLineIdString(nextProps.contract)
    ) {
      this.setState({ contract: nextProps.contract });
    }
  }

  formatMoneyString = (value) => {
    if (typeof value === "number" && !isNaN(value)) return value;
    if (typeof value === "string") return Number(value.replace(/,/g, ""));
    return 0;
  };

  editCurrentPay = (value, record) => {
    if (value && record.availableAmount > 0 && value > record.availableAmount) {
      message.error(messages("finance-9.key33") /*本次支付金额不能大于可关联金额*/);
      return 0;
    }
    const { contract } = this.state;
    let newContract = deepCopy(contract);
    newContract.map((item) => {
      if (item.contractLineId === record.contractLineId) {
        item.lineAvailableAmount = this.formatMoneyString(value);
      }
    });
    this.setState({ contract: newContract }, () => {
      let planedAmount = newContract.reduce((total, current) => total + (current.lineAvailableAmount || 0), 0);
      this.props.onRefreshPayInfoDetail(
        {
          contractAssociatedDTOList: newContract,
          planedAmount,
        },
        "edit"
      );
    });
  };

  onChangeContractLine = (value) => {
    let newContract = deepCopy(value.result || []);
    newContract = newContract.map((item) => {
      item.lineAvailableAmount = 0;
      return item;
    });
    this.setState({ contract: newContract, showContractLineList: false }, () => {
      let planedAmount = 0;
      this.props.onRefreshPayInfoDetail(
        {
          contractAssociatedDTOList: newContract,
          planedAmount,
        },
        "reset"
      );
    });
  };

  render() {
    const { contractColumns, showContractLineList, contract } = this.state;
    const { editable, expenseInfo, openContractDetail, single, entry } = this.props;
    return (
      <div>
        <Condition>
          <If value={contract[0] && contract[0].contractLineId}>
            <div className="associate-contract one-row">
              {editable && (
                <a className="expense-card-edit" onClick={() => this.setState({ showContractLineList: true })}>
                  {messages("common.edit") /*编辑*/}
                </a>
              )}
              <SVGIcon className="associate-contract-icon" type="report-info" />
              <div style={{ paddingLeft: 20, marginBottom: 12 }}>
                <div className="associate-contract-name">{messages("finance-9.key16") /*关联合同行*/}</div>
                <div className="associate-contract-info">
                  {messages("finance-9.key34") /*合同单号*/}：
                  {contract[0] ? (
                    editable || !openContractDetail ? (
                      contract[0].contractNumber
                    ) : (
                      <a onClick={() => openContractDetail(contract[0])}>{contract[0].contractNumber}</a>
                    )
                  ) : (
                    "-"
                  )}
                </div>
                <div className="associate-contract-info">
                  {messages("finance-9.key35") /*合同名称*/}：{contract[0] ? contract[0].contractName : "-"}
                </div>
                <div className="associate-contract-info">
                  {messages("finance-9.key36") /*合同类型*/}：{contract[0] ? contract[0].contractTypeName : "-"}
                </div>
              </div>
              <Table
                rowKey="id"
                columns={contractColumns}
                dataSource={contract || []}
                size="small"
                bordered
                pagination={false}
              />
            </div>
          </If>
          <Else>
            <Input
              onClick={() => this.setState({ showContractLineList: true })}
              className="normal-width"
              disabled={
                (!expenseInfo.contractHeaderId && expenseInfo.contractPosition === "DOCUMENTS_HEAD") ||
                entry === "audit"
              }
            />
          </Else>
        </Condition>

        <ListSelector
          visible={showContractLineList}
          type="choose_contract"
          extraParams={{
            documentType: "PUBLIC_REPORT",
            companyOID: expenseInfo.docCompanyOID,
            currency: expenseInfo.currencyCode,
            contractHeaderId: expenseInfo.contractHeaderId,
            partnerCategory: "VENDOR",
            applicantDepartmentOID: expenseInfo.applicantDepartmentOID,
          }}
          labelKey="contractNumber"
          valueKey="contractLineId"
          itemMap
          single={single}
          onOk={this.onChangeContractLine}
          onCancel={() => this.setState({ showContractLineList: false })}
          selectedData={contract}
        />
      </div>
    );
  }
}

AssociateContract.propsType = {};

AssociateContract.defaultProps = {};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    user: state.login.user,
    authPolicyAll: state.main.authPolicyAll,
    options: state.login.options,
    profile: state.login.profile,
  };
}

export default connect(mapStateToProps)(AssociateContract);
